package com.rongxun.api;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.rongxun.api.utils.FlyLog;
import com.rongxun.api.utils.NetworkUtil;
import com.rongxun.api.utils.SysUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 应用内信息
 */
public class AppSysInfoManager {


    private static Context mContext;


    private int osVersionCode;

    private String osVersion;

    private int versionCode;

    private String packageName;

    private String versionName;

    private String appName;
    /**
     * 手机厂商
     */
    private String brand;

    /**
     * GSM手机的 IMEI 和 CDMA手机的 MEID.
     */
    private String imei;

    private String imsi;
    /**
     * SIM卡的序列号：
     */
    private String sim;

    /**
     * The mobile mac address
     */
    private String macAddress;

    private String ssid;

    /**
     * The user-visible version string. E.g., "1.0"
     */
    private String buildVersion;
    /**
     * The mobile model such as "Nexus One" Attention: some model type may have
     * illegal characters
     */
    private String model;
    /**
     * The singleton instance
     */

    private String appSystem;


    private String androidId;
    private String phoneNumber;

    private List<NetworkChangedListener> networkChangedListeners;
    private String                       channel;
    private DownloadManager              mDownloadManager;
    private String                       userId;


    @SuppressLint("NewApi")
    private AppSysInfoManager() {
        osVersionCode = Build.VERSION.SDK_INT;
        buildVersion = Build.VERSION.RELEASE;
        try {
            model = URLEncoder.encode(Build.MODEL, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            model = Build.MODEL;
        }
        try {
            brand = URLEncoder.encode(Build.BRAND, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            brand = Build.BRAND;
        }
        try {
            osVersion = URLEncoder.encode(Build.VERSION.RELEASE, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            osVersion = Build.VERSION.RELEASE;
        }
        try {
            appSystem = URLEncoder.encode(Build.VERSION.RELEASE, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            appSystem = Build.VERSION.RELEASE;
        }

        networkChangedListeners = new ArrayList<NetworkChangedListener>();

        try {

            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            mContext.registerReceiver(mReceiver, filter);
        } catch (Exception e) {
        }


        ApplicationInfo appInfo = null;
        try {
            appInfo = mContext.getPackageManager()
                    .getApplicationInfo(mContext.getPackageName(),
                            PackageManager.GET_META_DATA);

            FlyLog.d(mContext.getPackageName());


            channel = appInfo.metaData.getString("UMENG_CHANNEL");


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void init(Context context) {
        mContext = context;
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {

                boolean networkAvailable = NetworkUtil.isNetworkAvailable(mContext);

                for (NetworkChangedListener networkChangedListener : networkChangedListeners) {
                    networkChangedListener.onNetworkStateChanged(networkAvailable);
                }
            }
        }
    };


    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }


    public String getAppSystem() {
        return appSystem;
    }

    public String getChannel() {
        return channel;
    }

    public void setChannel(String channel) {
        this.channel = channel;
    }

    public boolean isNetworkAvailable() {
        return NetworkUtil.isNetworkAvailable(mContext);
    }

    public void addNetworkChangedListener(NetworkChangedListener networkChangedListener) {
        this.networkChangedListeners.add(networkChangedListener);
    }

    public void removeNetworkChangedListener(NetworkChangedListener networkChangedListener) {
        networkChangedListeners.remove(networkChangedListener);
    }

    public static interface NetworkChangedListener {
        public void onNetworkStateChanged(boolean networkAvailable);
    }

    //    public DownloadManager getDownloadManager() {
    //        if (mDownloadManager == null) {
    //            mDownloadManager = new DownloadManager(mContext.getContentResolver(), getPackageName());
    //        }
    //        return mDownloadManager;
    //    }

    @SuppressLint("StaticFieldLeak")
    private static volatile AppSysInfoManager mInstance;

    public static AppSysInfoManager getInstance() {
        if (mInstance == null) {
            synchronized (AppSysInfoManager.class) {
                if (mInstance == null) {
                    mInstance = new AppSysInfoManager();
                }
            }
        }
        return mInstance;
    }


    public int getOsVersionInt() {
        return osVersionCode;
    }

    public String getOsVersion() {
        return osVersion;
    }


    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public String getDeviceBrand() {
        return brand;
    }

    public String getBuildVersion() {
        return buildVersion;
    }

    @SuppressLint({"MissingPermission", "HardwareIds"})
    private void getApplicationInfo() {

        final PackageManager pm = (PackageManager) mContext.getPackageManager();
        try {
            final PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), 0);

            versionName = pi.versionName;

            versionCode = pi.versionCode;

            int labelRes = pi.applicationInfo.labelRes;

            appName = mContext.getResources().getString(labelRes);

            packageName = mContext.getPackageName();

            TelephonyManager telMgr = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);

            imei = Settings.System.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);

            imei = getUniqueID(mContext);

////            imsi = telMgr.getSubscriberId();
//
//            sim = telMgr.getSimSerialNumber();
//
//            phoneNumber = telMgr.getLine1Number();

            androidId = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (NameNotFoundException e) {

        }
    }


    public static String getUniqueID(Context context) {
        String id = null;
        final String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        if (!TextUtils.isEmpty(androidId) && !"9774d56d682e549c".equals(androidId)) {
            try {
                UUID uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
                id = uuid.toString();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        if (TextUtils.isEmpty(id)) {
            id = getUUID();
        }

        return TextUtils.isEmpty(id) ? UUID.randomUUID().toString() : id;
    }

    @SuppressLint("MissingPermission")
    private static String getUUID() {
        String serial = null;

        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                serial = android.os.Build.getSerial();
            } else {
                serial = Build.SERIAL;
            }
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            serial = "serial"; // 随便一个初始化
        }

        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    public String getVersionName() {
        if (TextUtils.isEmpty(versionName)) {
            getApplicationInfo();
        }
        return versionName;
    }

    public int getVersionCode() {
        if (versionCode <= 0) {
            getApplicationInfo();
        }
        return versionCode;
    }

    public String getIMEI() {
        if (TextUtils.isEmpty(imei)) {
            getApplicationInfo();
        }
        return imei;
    }

    public String getPackageName() {
        if (TextUtils.isEmpty(packageName)) {
            getApplicationInfo();
        }
        return packageName;
    }

    public String getSim() {
        if (TextUtils.isEmpty(sim)) {
            getApplicationInfo();
        }
        return sim;
    }

    public String getIMSI() {
        if (TextUtils.isEmpty(imsi)) {
            getApplicationInfo();
        }
        return imsi;
    }

    /**
     * 检索找到设备的Wi-Fi或蓝牙硬件的Mac地址。但是，不推荐使用Mac地址作为唯一的标识号。因为设备要具备Wi-Fi功能（并非所有的设备都有Wi-
     * Fi功能） 如果设备目前正在使用Wi-Fi，则不能报告Mac地址
     *
     * @return mac地址
     */
    public String getMac() {
        if (TextUtils.isEmpty(macAddress)) {
            getWifiInfo();
        }
        return macAddress;
    }

    public String getSsid() {
        if (TextUtils.isEmpty(ssid)) {
            getWifiInfo();
        }
        return ssid;
    }

    private void getWifiInfo() {
        WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        macAddress = info.getMacAddress();
        ssid = info.getSSID();
    }

    public String getAppName() {
        return appName;
    }

    public String getModel() {
        return model;
    }

    /**
     * GSM手机的 IMEI 和 CDMA手机的 MEID. Return null if device ID is not available.
     *
     * @return 唯一的设备ID
     */
    /**
     * Settings.Secure.ANDROID_ID
     * 是一串64位的编码（十六进制的字符串），是随机生成的设备的第一个引导，其记录着一个固定值，通过它可以知道设备的寿命
     * （在设备恢复出厂设置后，该值可能会改变）。 ANDROID_ID也可视为作为唯一设备标识号的一个好选择。如要检索用于设备ID
     * 的ANDROID_ID
     * <p>
     * <pre>
     *  缺点
     * • 对于Android 2.2（“Froyo”）之前的设备不是100％的可靠
     * • 此外，在主流制造商的畅销手机中至少存在一个众所周知的错误，每一个实例都具有相同的ANDROID_ID。
     * </pre>
     *
     * @return
     */
    public String getAndroidId() {
        if (androidId == null)
            getApplicationInfo();
        return androidId;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    private String deviceId;

    public String getDeviceId() {
        if (TextUtils.isEmpty(deviceId))
            deviceId = SysUtils.md5(getIMEI(), getMac(), getAndroidId());
        return deviceId;
    }

}